﻿using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using EdlinSoftware.RegexTester.Code;
using EdlinSoftware.RegexTester.Properties;

namespace EdlinSoftware.RegexTester.Controls
{
    public partial class FileShortcuts : UserControl
    {
        #region Fields

        private static readonly Regex _fileShortcutRegex = new Regex(@"^([^:\s]+)\s+encoding\s+:\s+(.+)$");

        #endregion

        #region Properties

        [Browsable(false)]
        public TextBox TextBox { get; set; }

        #endregion

        #region Constructors

        public FileShortcuts()
        {
            InitializeComponent();
        }

        #endregion

        #region Methods

        public void ShowFileShortcuts()
        {
            while (Controls.Count > 1)
            { Controls.RemoveAt(0); }

            int index = 1;
            foreach (string shortcut in new FileShortcutsProvider().GetAllFileShortcuts().Reverse())
            {
                Match match = _fileShortcutRegex.Match(shortcut);
                string fileName = match.Groups[2].Value;

                Button button = new Button();
                button.Text = Resources.Text + " " + index;
                button.Tag = shortcut;
                button.Dock = DockStyle.Top;
                button.Margin = new Padding(5);
                toolTip.SetToolTip(button, string.Format(Resources.LoadFileShortcut, fileName));
                button.Click += new EventHandler(LoadTextFromFile);

                Controls.Add(button);
                Controls.SetChildIndex(button, 0);

                index++;
            }
        }

        void LoadTextFromFile(object sender, EventArgs e)
        {
            Button button = (Button)sender;

            string shortcut = (string)button.Tag;

            Match match = _fileShortcutRegex.Match(shortcut);
            string filePath = match.Groups[2].Value;

            Encoding encoding;
            switch (match.Groups[1].Value)
            {
                case "UTF8":
                    {
                        encoding = Encoding.UTF8;
                        break;
                    }
                case "Unicode":
                    {
                        encoding = Encoding.Unicode;
                        break;
                    }
                default:
                    {
                        encoding = Encoding.Default;
                        break;
                    }
            }

            TextBox.Text = File.ReadAllText(filePath, encoding);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            TextBox.Clear();
        }

        #endregion
    }
}
